﻿using DiLe.Mes.Application.Common;
using DiLe.Mes.Application.Common.Equipment;
using DiLe.Mes.Application.Common.Equipment.ViewModel;
using DiLe.Mes.Model.Common.Equipment.Entity.Maintenance;
using DiLe.Mes.Model.Common.Equipment.Entity.Manage;
using DiLe.Mes.Model.Common.Equipment.Entity.Repair;
using DiLe.Mes.Model.Common.Equipment.Entity.SparePart;
using DiLe.Mes.Model.Common.System.Entity;

namespace DiLe.Mes.Application.Handler {
    /// <summary>
    /// 
    /// </summary>
    public class EquipmentExjosnHandler {
        private readonly SystemClient _systemClient;
        private readonly EquipmentManageClient _equipmentClient;
        private readonly OrganizationClient _organizationClient;
        private readonly SparePartManageClient _sparePartClient;
        private readonly EquipmentMaintenanceClient _maintenanceClient;
        private readonly EquipmentRepairClient _equipmentRepairClient;
        /// <summary>
        /// 构造函数
        /// </summary>
        public EquipmentExjosnHandler(SystemClient systemClient,
                                      OrganizationClient organizationClient,
                                      EquipmentManageClient equipmentClient,
                                      SparePartManageClient sparePartClient,
                                      EquipmentMaintenanceClient maintenanceClient,
                                      EquipmentRepairClient equipmentRepairClient) {
            _systemClient = systemClient;
            _organizationClient = organizationClient;
            _equipmentClient = equipmentClient;
            _sparePartClient = sparePartClient;
            _maintenanceClient = maintenanceClient;
            _equipmentRepairClient = equipmentRepairClient;
        }

        #region info
        /// <summary>
        /// 填充设备档案的额外字段
        /// </summary>
        /// <param name="dataList"></param>
        public async Task FillEquipmentInfoExjosn(List<EquipmentInfoEntity> dataList) {
            if (!dataList.Any()) {
                return;
            }
            //部门
            var departmentIds = dataList.Where(x => x.DepartmentId != null).Select(p => p.DepartmentId!.Value).Distinct().ToList();
            var departmentList = await _organizationClient.GetOrganizationListAsync(departmentIds);
            //负责人
            var userIds = dataList.Where(x => x.Manager != null).Select(p => p.Manager!.Value).Distinct().ToList();
            var userList = await _organizationClient.GetUserListByIdAsync(userIds);
            //类型
            var typeIds = dataList.Select(p => p.TypeId).Distinct().ToList();
            var typeList = await _equipmentClient.GetEquipmentTypeListAsync(typeIds);
            //状态
            var statusIds = dataList.Where(x => x.CurrentStatus != null).Select(p => p.CurrentStatus).Distinct().ToList();
            var statusList = await _equipmentClient.GetEquipmentStatusListAsync(p => statusIds.Contains(p.Id));
            //位置
            var positionIds = dataList.Where(x => x.PositionId != null).Select(p => p.PositionId).Distinct().ToList();
            var positionList = await _systemClient.GetPositionListAsync(p => positionIds.Contains(p.Id));
            //工厂
            var factoryIds = dataList.Where(x => x.FactoryId != null).Select(p => p.FactoryId).Distinct().ToList();
            var factoryList = await _organizationClient.GetOrganizationListAsync(p => factoryIds.Contains(p.Id));

            foreach (var item in dataList) {
                var department = departmentList?.FirstOrDefault(p => p.Id == item.DepartmentId);
                item.ExtJson.Add("DepartmentName", department?.Name);
                var manager = userList?.FirstOrDefault(p => p.Id == item.Manager);
                item.ExtJson.Add("ManagerName", manager?.Name);
                var type = typeList?.FirstOrDefault(p => p.Id == item.TypeId);
                item.ExtJson.Add("TypeName", type?.Name);
                var status = statusList?.FirstOrDefault(p => p.Id == item.CurrentStatus);
                item.ExtJson.Add("StatusName", status?.Name);
                var position = positionList?.FirstOrDefault(p => p.Id == item.PositionId);
                item.ExtJson.Add("PositionName", position?.Position);
                var factory = factoryList?.FirstOrDefault(p => p.Id == item.FactoryId);
                item.ExtJson.Add("FactoryName", factory?.Name);
            }
        }


        /// <summary>
        /// 填充设备注册信息的额外字段
        /// </summary>
        /// <returns></returns>
        public async Task<List<EquipmentRegisterDto>> GetEquipmentRegisterExjosn(List<EquipmentRegisterEntity> dataList) {
            var list = new List<EquipmentRegisterDto>();
            if (dataList.None()) {
                return list;
            }
            //设备
            var equipmentIds = dataList.Select(p => p.EquipmentInfoId).Distinct().ToList();
            var equipmentList = await _equipmentClient.GetEquipmentInfoListAsync(equipmentIds);
            await FillEquipmentInfoExjosn(equipmentList);
            foreach (var item in dataList) {
                var dto = new EquipmentRegisterDto {
                    Model = item,
                    Equipment = equipmentList.FirstOrDefault(p => p.Id == item.EquipmentInfoId) ?? new EquipmentInfoEntity()
                };
                list.Add(dto);
            }
            return list;
        }

        #endregion
        #region Maintenance
        /// <summary>
        /// 填充保养项目的额外字段
        /// </summary>
        /// <param name="dataList"></param>
        public async Task FillMaintenanceProjectExjosn(List<MaintenanceProjectEntity> dataList) {
            if (!dataList.Any()) {
                return;
            }
            //设备类型
            var typeIds = dataList.Select(p => p.MaintenanceType).Distinct().ToList();
            var typeList = await _equipmentClient.GetEquipmentTypeListAsync(p => typeIds.Contains(p.Id));
            //保养级别
            var levelIds = dataList.Select(p => p.MaintenanceLevel).Distinct().ToList();
            var levelList = await _systemClient.GetMaintenanceLevelListAsync(p => levelIds.Contains(p.Id));

            foreach (var item in dataList) {
                var type = typeList?.FirstOrDefault(p => p.Id == item.MaintenanceType);
                item.ExtJson.Add("MaintenanceTypeName", type?.Name);

                var level = levelList?.FirstOrDefault(p => p.Id == item.MaintenanceLevel);
                item.ExtJson.Add("MaintenanceLevelName", level?.Name);
            }
        }
        /// <summary>
        /// 获取保养计划视图模型列表
        /// </summary>
        /// <param name="dataList"></param>
        /// <returns></returns>
        public async Task<List<MaintenancePlanDto>> GetMaintenancePlanDto(List<MaintenancePlanEntity> dataList) {
            var list = new List<MaintenancePlanDto>();
            if (!dataList.Any()) {
                return list;
            }
            await FillMaintenancePlanExjosn(dataList);
            //设备
            var equipmentIds = dataList.Select(p => p.EquipmentId).Distinct().ToList();
            var equipmentList = await _equipmentClient.GetEquipmentInfoListAsync(p => equipmentIds.Contains(p.Id));
            await FillEquipmentInfoExjosn(equipmentList);
            //规则
            var executeRuleIds = dataList.Select(p => p.ExecuteRuleId).Distinct().ToList();
            var executeRuleList = await _systemClient.GetExecuteRuleListAsync(p => executeRuleIds.Contains(p.Id));
            foreach (var item in dataList) {
                var dto = new MaintenancePlanDto();
                dto.Model = item;
                dto.EquipmentModel = equipmentList.FirstOrDefault(p => p.Id == item.EquipmentId) ?? new EquipmentInfoEntity();
                dto.ExecuteRuleModel = executeRuleList.FirstOrDefault(p => p.Id == item.ExecuteRuleId) ?? new ExecuteRuleEntity();
                list.Add(dto);
            }
            return list;
        }
        /// <summary>
        /// 填充保养计划的额外字段
        /// </summary>
        /// <param name="dataList"></param>
        /// <returns></returns>
        public async Task FillMaintenancePlanExjosn(List<MaintenancePlanEntity> dataList) {
            if (!dataList.Any()) {
                return;
            }
            var userList = await _organizationClient.GetUserListAsync();
            //班组
            var teamIds = dataList.Select(p => p.TeamId).Distinct().ToList();
            var teamList = await _systemClient.GetTeamListAsync(p => teamIds.Contains(p.Id));
            //规则
            var executeRuleIds = dataList.Select(p => p.ExecuteRuleId).Distinct().ToList();
            var executeRuleList = await _systemClient.GetExecuteRuleListAsync(p => executeRuleIds.Contains(p.Id));

            foreach (var item in dataList) {
                var manager = userList?.FirstOrDefault(p => p.Id == item.Manager);
                item.ExtJson.Add("ManagerName", manager?.Name);

                var team = teamList?.FirstOrDefault(p => p.Id == item.TeamId);
                item.ExtJson.Add("TeamName", team?.Name);

                var users = userList?.Where(p => item.OtherUserIds.Contains(p.Id)).ToList();
                if (!users.None()) {
                    item.ExtJson.Add("OtherPeopleName", string.Join(",", users!.ConvertAll(p => p.Name)));
                }
                var executeRule = executeRuleList?.FirstOrDefault(p => p.Id == item.ExecuteRuleId);
                item.ExtJson.Add("ExecuteRuleName", executeRule?.Name);
                item.ExtJson.Add("ExecuteRuleDescription", executeRule?.RuleDescription);
            }
        }
        /// <summary>
        /// 获取保养记录视图模型列表
        /// </summary>
        /// <param name="dataList"></param>
        /// <returns></returns>
        public async Task<List<MaintenanceRecordDto>> GetMaintenanceRecordDto(List<MaintenanceRecordEntity> dataList) {
            var list = new List<MaintenanceRecordDto>();
            if (!dataList.Any()) {
                return list;
            }
            var userList = await _organizationClient.GetUserListAsync();
            //计划
            var planIds = dataList.Select(p => p.MaintenancePlanId).Distinct().ToList();
            var planList = await _maintenanceClient.GetMaintenancePlanListAsync(p => planIds.Contains(p.Id));
            await FillMaintenancePlanExjosn(planList);
            //设备
            var equipmentIds = dataList.Select(p => p.EquipmentId).Distinct().ToList();
            var equipmentList = await _equipmentClient.GetEquipmentInfoListAsync(p => equipmentIds.Contains(p.Id));
            await FillEquipmentInfoExjosn(equipmentList);

            foreach (var item in dataList) {
                var dto = new MaintenanceRecordDto();
                dto.Model = item;
                dto.PlanModel = planList?.FirstOrDefault(p => p.Id == item.MaintenancePlanId) ?? new MaintenancePlanEntity();
                dto.EquipmentModel = equipmentList?.FirstOrDefault(p => p.Id == item.EquipmentId) ?? new EquipmentInfoEntity();
                list.Add(dto);
            }
            return list;
        }
        /// <summary>
        /// 填充保养记录的额外字段
        /// </summary>
        /// <param name="dataList"></param>
        /// <returns></returns>
        public async Task FillMaintenanceRecordExjosn(List<MaintenanceRecordEntity> dataList) {
            if (!dataList.Any()) {
                return;
            }
            var userList = await _organizationClient.GetUserListAsync();
        }
        #endregion
        #region Repair
        /// <summary>
        /// 获取保养记录视图模型列表
        /// </summary>
        /// <param name="dataList"></param>
        /// <returns></returns>
        public async Task<List<RepairRecordDto>> GetRepairRecordDto(List<RepairRecordEntity> dataList) {
            var list = new List<RepairRecordDto>();
            if (!dataList.Any()) {
                return list;
            }
            await FillRepairRecordExjosn(dataList);
            //设备
            var equipmentIds = dataList.Select(p => p.EquipmentId).Distinct().ToList();
            var equipmentList = await _equipmentClient.GetEquipmentInfoListAsync(p => equipmentIds.Contains(p.Id));
            await FillEquipmentInfoExjosn(equipmentList);

            foreach (var item in dataList) {
                var dto = new RepairRecordDto();
                dto.Model = item;
                dto.EquipmentModel = equipmentList?.FirstOrDefault(p => p.Id == item.EquipmentId) ?? new EquipmentInfoEntity();
                list.Add(dto);
            }
            return list;
        }

        /// <summary>
        /// 填充维修记录的额外字段
        /// </summary>
        /// <param name="dataList"></param>
        public async Task FillRepairRecordExjosn(List<RepairRecordEntity> dataList) {
            if (!dataList.Any()) {
                return;
            }
            var userList = await _organizationClient.GetUserListAsync();
            //故障类型
            var faultTypeIds = dataList.Select(p => p.FaultType).Distinct().ToList();
            var faultTypeList = await _equipmentRepairClient.GetRepairTypeListAsync(p => faultTypeIds.Contains(p.Id));
            //班组
            var teamIds = dataList.Select(p => p.TeamId).Distinct().ToList();
            var teamList = await _systemClient.GetTeamListAsync(p => teamIds.Contains(p.Id));
            //仓库
            var warehouseIds = dataList.Select(p => p.WarehouseId).Distinct().ToList();
            var warehouseList = await _systemClient.GetWarehouseListAsync(p => warehouseIds.Contains(p.Id));
            foreach (var item in dataList) {
                var team = teamList?.FirstOrDefault(p => p.Id == item.TeamId);
                item.ExtJson.Add("TeamName", team?.Name);

                var faultType = faultTypeList?.FirstOrDefault(p => p.Id == item.FaultType);
                item.ExtJson.Add("FaultTypeName", faultType?.Name);

                var manager = userList?.FirstOrDefault(p => p.Id == item.Manager);
                item.ExtJson.Add("ManagerName", manager?.Name);

                var warehouse = warehouseList?.FirstOrDefault(p => p.Id == item.WarehouseId);
                item.ExtJson.Add("WarehouseName", warehouse?.Name);

                var users = userList?.Where(p => item.PersonnelList.Contains(p.Id)).ToList();
                if (!users.None()) {
                    item.ExtJson.Add("PersonnelNames", string.Join(",", users!.ConvertAll(p => p.Name)));
                }

            }
        }
        #endregion
        #region SparePart 备件
        /// <summary>
        /// 填充备件台账的额外字段
        /// </summary>
        /// <param name="dataList"></param>
        public async Task<List<SparePartLedgerDetailDto>> FillSparePartLedgerExjosn(List<SparePartLedgerEntity> dataList) {
            List<SparePartLedgerDetailDto> list = new();
            if (!dataList.Any()) {
                return list;
            }
            //类型
            var typeIds = dataList.Select(p => p.TypeId).Distinct().ToList();
            var typeList = await _sparePartClient.GetSparePartTypeListAsync(p => typeIds.Contains(p.Id));
            //单位
            var unitIds = dataList.Select(p => p.Unit).Distinct().ToList();
            var unitList = await _systemClient.GetMeasureUnitListAsync(p => unitIds.Contains(p.Id));
            //库存
            var inventoryIds = dataList.ConvertAll(p => p.Id);
            var inventoryList = await _systemClient.GetSparePartInventoryListAsync(x => inventoryIds.Contains(x.SparePartId));
            foreach (var data in dataList) {
                var item = data.Adapt<SparePartLedgerDetailDto>();
                var type = typeList?.FirstOrDefault(p => p.Id == item.TypeId);
                item.ExtJson.Add("TypeName", type?.Name);
                var unit = unitList?.FirstOrDefault(p => p.Id == item.Unit);
                item.ExtJson.Add("UnitName", unit?.Name);
                var inventory = inventoryList?.FirstOrDefault(p => p.SparePartId == item.Id);
                item.InventoryTotalLimit = inventory?.InventoryQuantity ?? 0;
                list.Add(item);
            }
            return list;
        }
        /// <summary>
        /// 填充备件台账的额外字段
        /// </summary>
        /// <param name="data"></param>
        public async Task<SparePartLedgerDetailDto> FillSparePartLedgerExjosn(SparePartLedgerEntity data) {
            SparePartLedgerDetailDto result = new();
            if (data == null) {
                return result;
            }
            //类型
            var type = await _sparePartClient.GetSparePartTypeAsync(data.TypeId);
            //单位
            var unit = await _systemClient.GetMeasureUnitInfoAsync(data.Unit);
            //库存
            var inventory = await _systemClient.GetSparePartInventoryAsync(x => x.SparePartId == data.Id);

            result = data.Adapt<SparePartLedgerDetailDto>();
            result.ExtJson.Add("TypeName", type?.Name);
            result.ExtJson.Add("UnitName", unit?.Name);
            result.InventoryTotalLimit = inventory?.InventoryQuantity ?? 0;
            return result;
        }

        /// <summary>
        /// 填充备件入库的额外字段
        /// </summary>
        /// <param name="dataList"></param>
        public async Task FillSparePartStockInExjosn(List<SparePartStockInEntity> dataList) {
            if (!dataList.Any()) {
                return;
            }
            //仓库
            var warehouseIds = dataList.Select(p => p.WarehouseId).Distinct().ToList();
            var warehouseList = await _systemClient.GetWarehouseListAsync(p => warehouseIds.Contains(p.Id));
            //用户
            var useIds = warehouseList?.ConvertAll(p => p.Manager) ?? new List<long>();
            var userList = await _organizationClient.GetUserListAsync(p => useIds.Contains(p.Id));

            foreach (var item in dataList) {
                var warehouse = warehouseList?.FirstOrDefault(p => p.Id == item.WarehouseId);
                item.ExtJson.Add("WarehouseName", warehouse?.Name);
                var user = userList?.FirstOrDefault(p => p.Id == warehouse?.Manager);
                item.ExtJson.Add("WarehouseManagerName", user?.Name);

            }
        }
        /// <summary>
        /// 填充备件出库的额外字段
        /// </summary>
        /// <param name="dataList"></param>
        public async Task FillSparePartStockOutExjosn(List<SparePartStockOutEntity> dataList) {
            if (!dataList.Any()) {
                return;
            }
            //负责人
            var userList = await _organizationClient.GetUserListAsync();
            //部门
            var departmentList = await _organizationClient.GetOrganizationListAsync();

            //仓库
            var warehouseIds = dataList.Select(p => p.WarehouseId).Distinct().ToList();
            var warehouseList = await _systemClient.GetWarehouseListAsync(p => warehouseIds.Contains(p.Id));
            //出库关联
            var ids = dataList.ConvertAll(p => p.Id);
            var rels = await _sparePartClient.GetStockOutSparePartList(p => ids.Contains(p.StockOutId));

            foreach (var item in dataList) {
                var warehouse = warehouseList?.FirstOrDefault(p => p.Id == item.WarehouseId);
                item.ExtJson.Add("WarehouseName", warehouse?.Name);

                var warehouseManager = userList?.FirstOrDefault(p => p.Id == warehouse?.Manager);
                item.ExtJson.Add("WarehouseManagerName", warehouseManager?.Name);
                //申请人
                var applicant = userList?.FirstOrDefault(p => p.Id == item.Applicant);
                item.ExtJson.Add("ApplicantName", applicant?.Name);
                //所在部门  
                var applicantdepartment = departmentList?.FirstOrDefault(p => p.Id == applicant?.DepartmentId);
                item.ExtJson.Add("ApplicantDepartmentName", applicantdepartment?.Name);
                //出库人员
                var stockoutuser = userList?.FirstOrDefault(p => p.Id == item.StockOutUserId);
                item.ExtJson.Add("StockOutUserName", stockoutuser?.Name);

                //出库数量
                var stockoutnumber = rels?.Where(p => p.StockOutId == item.Id).Sum(p => p.StockOutNumber);
                item.ExtJson.Add("StockOutUserNum", stockoutnumber);

            }
        }
        #endregion








    }
}
